package ying.response;/**
 * ClassName: ResponseDemo05
 * Package: ying.response
 * Description:
 *
 * @Author 刘英杰
 * @Create 2024/10/3 18:11
 * @Version 1.0
 */

/**
 * HttpServletResponse中的方法
 *  getOutputStream():获取一个字节输出流
 * ServletContext中的方法
 *   getMimeType(String fileName):根据指定的名称返回对应的MIME类型
 */

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/resp/demo05")
public class ResponseDemo05 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletOutputStream os = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(os);

        //设置响应内容的MIME类型
        response.setContentType(getServletContext().getMimeType("1.jpg"));
//        response.setHeader("Content-Type", getServletContext().getMimeType("1.jpg"));
        
        //通过字节输出流将字节写给浏览器
        InputStream is = getServletContext().getResourceAsStream("/1.jpg");
        BufferedInputStream bis = new BufferedInputStream(is);

        int b;
        while( (b = bis.read()) != -1 ) {
            bos.write(b);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
